import errorCode from '@/constants/Errors'
import loginHelper from '@/pluginHelper/login'

export type ErrorType = {
  statusCode?: number
  code?: number
  data?: {
    key?: string
  }
  msg?: string
}
export function useErrors() {
  let errorTipsText = ref('')
  let errorTipsFlag = ref(false)

  function handleCommonShareError(error: ErrorType) {
    if (error.statusCode === 502) {
      errorTipsFlag.value = true
      errorTipsText.value = '服务器错误'
    }
    let trans = false
    if (error.data === null) {
      for (let i = 0; i < errorCode.length; i++) {
        if (Number(errorCode[i].code) === error.code) {
          trans = true
          showShareErrorMsg(i)
        }
      }
      if (!trans) {
        errorTipsFlag.value = true
        errorTipsText.value = error.msg || ''
      }
    } else if (error.data?.key !== null) {
      for (let j = 0; j < errorCode.length; j++) {
        if (errorCode[j].key === error.data?.key) {
          trans = true
          showShareErrorMsg(j)
        }
      }
      if (!trans) {
        for (let k = 0; k < errorCode.length; k++) {
          if (Number(errorCode[k].code) === error.code) {
            trans = true
            showShareErrorMsg(k)
          }
        }
      }
      if (!trans) {
        errorTipsFlag.value = true
        errorTipsText.value = error.msg || ''
      }
    }
  }

  function showShareErrorMsg(i: number) {
    if (errorCode[i].action === 3) {
      errorTipsText.value = errorCode[i].translation
      errorTipsFlag.value = true
      setTimeout(function () {
        errorTipsFlag.value = false
        uni.removeStorageSync('ciamId')
        loginHelper.noCiamIdLogin()
      }, 1500)
      return
    } else {
      errorTipsFlag.value = true
      errorTipsText.value = errorCode[i].translation
    }
  }

  return {
    errorTipsFlag,
    errorTipsText,
    handleCommonShareError,
  }
}
